package com.shigu.mo.actions;

import com.shigu.agent.enums.UserRoleType;
import com.shigu.agent.exceptions.AgentException;
import com.shigu.agent.exceptions.YeepayException;
import com.shigu.component.shiro.AuthorityUser;
import com.shigu.component.shiro.CaptchaUsernamePasswordToken;
import com.shigu.mo.bo.requests.*;
import com.shigu.mo.enums.SessionEnum;
import com.shigu.mo.exceptions.MoException;
import com.shigu.mo.services.AgentService;
import com.shigu.mo.services.OverallSituationService;
import com.shigu.mo.vo.AgentBusinessCountVO;
import com.shigu.mo.vo.AgentMoneyVO;
import com.shigu.mo.vo.responses.*;
import com.shigu.passageway.exceptions.PassagewayException;
import com.shigu.wx.web.services.WxOpenidService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 代理的相关操作
 */
@Controller
@RequestMapping("ag")
public class AgentController {
    private static final Logger logger = LoggerFactory.getLogger(AgentController.class);

    @Autowired
    AgentService agentService;

    @Autowired
    WxOpenidService wxOpenidService;

    @Value("${main_host}")
    private String host;

    @Value("${system.rate}")
    private Double systemRate;
    /**
     * 登出
     * @return
     */
    @RequestMapping("loginOut")
    @ResponseBody
    public LogoutResponse loginOut(HttpSession session){
        LogoutResponse response=new LogoutResponse();
        Subject currentUser = SecurityUtils.getSubject();
        String openid= (String) currentUser.getSession().getAttribute(SessionEnum.WX_LOGEDUSER.toString());
        currentUser.logout();
        wxOpenidService.logout(openid);
        return response.success();
    }

    /**
     * 未提现金额
     * @return
     */
    @RequestMapping("getNoWithdralWalMoney")
    @ResponseBody
    public NoWithdralResponse getNoWithdralWalMoney(HttpSession session) throws MoException {
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        NoWithdralResponse response=new NoWithdralResponse();
        response.setNoWithdrawalMoney(agentService.selMoneyLeft(auth.getUserId()));
        return response.success();
    }

    /**
     * 提交代理提现金额
     * @return
     */
    @RequestMapping("submitAgentWithdrawalToServer")
    @ResponseBody
    public SubmitWithdralResponse submitAgentWithdrawalToServer(@Valid SubmitWithdralRequest bo,BindingResult result,HttpSession session) throws MoException, AgentException {
        SubmitWithdralResponse response=new SubmitWithdralResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        agentService.transferToCustomer(auth.getUserId(),Double.valueOf(bo.getWithdrawalMoney()));
        return response.success();
    }
    /**
     * 代理登陆
     * @param bo
     * @param result
     * @param request
     * @return
     */
    @RequestMapping("toAgentLogin")
    @ResponseBody
    public AgentLoginResponse toAgentLogin(@Valid AgentLoginRequest bo, BindingResult result,HttpSession session, HttpServletRequest request) throws IOException {
        AgentLoginResponse response=new AgentLoginResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        Subject currentUser = SecurityUtils.getSubject();
        String openid= (String) session.getAttribute(SessionEnum.WX_LOGEDUSER.toString());
        CaptchaUsernamePasswordToken token = new CaptchaUsernamePasswordToken(bo.getOemtag(),
                bo.getTelephone(), bo.getPassword(), false, request.getRemoteAddr(), "");
        token.setRememberMe(true);
        try {
            currentUser.login(token);
            AuthorityUser auth= (AuthorityUser) currentUser.getSession().getAttribute(SessionEnum.LOGIN_USER.toString());
            wxOpenidService.login(openid,auth.getUserId());
            if (!currentUser.hasRole(UserRoleType.AGENT.getValue())) {//不是商户不能登陆
                currentUser.logout();
                wxOpenidService.logout(openid);
//                return response.error("本账户没有代理权限");
                response.setNoRole(true);
            }
        } catch (AuthenticationException e) {
            return response.error("账号或密码错误");
        }
        return response.success();
    }

    /**
     * 得到代理数据
     * @return
     */
    @RequestMapping("getAgentUserData")
    @ResponseBody
    public AgentUserResponse getAgentUserData(HttpSession session) throws MoException {
        AgentUserResponse response=new AgentUserResponse();
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        response.setUserName(auth.getNick());
        AgentMoneyVO moneyVO=agentService.selMoneyByUserId(auth.getUserId());
        String headUrl=agentService.selHeadUrl(auth.getUserId());
        if (StringUtils.isNotEmpty(headUrl)) {
            response.setUserImg(headUrl);
        }
        response.setCostRates(agentService.costRates(auth.getUserId()));
        response.setNoWithdrawalMoney(moneyVO.getMoneyLeft());
        return response.success();
    }

    /**
     * 获取代理提现数据
     * @return
     */
    @RequestMapping("getWithdrawalData")
    @ResponseBody
    public WithdrawalRecordResponse getWithdrawalData(WithdrawalRecordRequest bo,HttpSession session){
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        WithdrawalRecordResponse response=new WithdrawalRecordResponse();
        Date d=null;
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotEmpty(bo.getSearchTime())) {
            try {
                d=sdf.parse(bo.getSearchTime());
            } catch (ParseException e) {
                logger.error("日期格式错误"+bo.getSearchTime(),e);
            }
        }
        response.setRecordList(agentService.cashRecords(auth.getUserId(),d));
        return response.success();
    }

    /**
     * 获取验证码图片
     * @return
     */
    @RequestMapping("agentQrCodeImg")
    @ResponseBody
    public QrCodeResponse agentQrCodeImg(HttpSession session){
        QrCodeResponse response=new QrCodeResponse();
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
//        response.setUrl(host+"wappage/buspage/regedit/from"+auth.getUserId());
        response.setUrl(host+"wap/qrimg.htm");
        return response.success();
    }

    /**
     * 获取代理交易数据
     * @return
     */
    @RequestMapping("getAgentTradeData")
    @ResponseBody
    public AgentTradeDataResponse getAgentTradeData(HttpSession session){
        AgentTradeDataResponse response=new AgentTradeDataResponse();
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        response.setTradeList(agentService.agentTradeCount(auth.getUserId()));
        return response.success();
    }

    /**
     * 详细分润列表
     * @param session
     * @return
     */
    @RequestMapping("getTradeDetailData")
    @ResponseBody
    public AgentTradeDetailResponse getTradeDetailData(Integer page,HttpSession session){
        if (page == null||page<=0) {
            page=1;
        }
        AgentTradeDetailResponse response=new AgentTradeDetailResponse();
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        response.setTradeList(agentService.tradeDetails(auth.getUserId(),page));
        return response.success();
    }

    /**
     * 查看商户列表
     * @return
     */
    @RequestMapping("busList")
    @ResponseBody
    public AgentBusListResponse busList(AgentBusListRequest bo,HttpSession session){
        AgentBusListResponse response=new AgentBusListResponse();
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        AgentBusinessCountVO countVO=agentService.businessCount(auth.getUserId());
        response.setAllbus(countVO.getAllbus());
        response.setTodayIncrease(countVO.getTodayIncrease());
        response.setWeekIncrease(countVO.getWeekIncrease());
        response.setBusList(agentService.selAgentBusiness(auth.getUserId(),bo.getType(),bo.getPage()));
        response.setHasNext(agentService.hasNextPageBusiness(auth.getUserId(),bo.getType(),bo.getPage()));
        return response.success();
    }

    /**
     * 查某商户的费率
     * @param bo
     * @return
     */
    @RequestMapping("selBusRate")
    @ResponseBody
    public AgentSelBusrateResponse selBusRate(AgentSelBusrateRequest bo){
        return agentService.selBusRate(bo.getBusId());
    }

    /**
     * 修改商户费率
     * @return
     */
    @RequestMapping("modifyBusRate")
    @ResponseBody
    public AgentModifyRateResponse modifyBusRate(@Valid AgentModifyRateRequest bo,BindingResult result,HttpSession session) throws MoException, PassagewayException {
        AgentModifyRateResponse response=new AgentModifyRateResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        Long agentId=auth.getUserId();
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.hasRole("worker1")) {
            agentId=agentService.selAgentId(bo.getBusId());
        }
        agentService.modifyRate(bo.getPid(),agentId,bo.getBusId(),bo.getRateDouble());
        return response.success();
    }

    /**
     * 把用户提升为代理
     * @return
     */
    @RequestMapping("setUserToAgent")
    @ResponseBody
    public MoResponse setUserToAgent(String bodyId,Double rate) throws IOException, MoException, PassagewayException {
        MoResponse response=new MoResponse();
        Subject currentUser = SecurityUtils.getSubject();
        if (!currentUser.hasRole("worker1")) {
            return response.success("用户权限不够");
        }
        if (rate>0.008d) {
            throw new MoException("费率过高，0.5%需要表达为0.005");
        }
        if (StringUtils.isEmpty(bodyId)||rate<systemRate) {
            throw new MoException("参数异常");
        }
        agentService.userUpToAgent(bodyId,rate);
        return response.success("提升成功");
    }

    /**
     * 费率详情
     */
    @RequestMapping("selRateDetail")
    @ResponseBody
    public RateDetailResponse selRateDetail(RateDetailRequest bo,HttpSession session) throws MoException {
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        RateDetailResponse response=agentService.selRateDetail(auth.getUserId(),bo.getBusId(),bo.getPid());
        return response.success();
    }

    /**
     * 拓展商户
     * @param session
     * @return
     */
    @RequestMapping("toInvite")
    public String toInvite(HttpSession session){
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        return "redirect:/wappage/agpage/agentInvite/"+auth.getUserId();
    }

}
